package com.delio.client.pagos.pagoadelantos;

import java.util.ArrayList;
import java.util.List;

import com.delio.client.idioma.DelioConstants;
import com.delio.client.idioma.DelioMessages;
import com.delio.client.util.Utilities;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.grid.AggregationRowConfig;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.grid.SummaryType;
import com.extjs.gxt.ui.client.widget.grid.filters.GridFilters;
import com.extjs.gxt.ui.client.widget.grid.filters.StringFilter;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.NumberFormat;

public class PanelGridPagoAdelanto  extends ContentPanel {
	private DelioConstants k = GWT.create(DelioConstants.class);
	private DelioMessages msg = GWT.create(DelioMessages.class);

	private Button btnDelete;
	private ToolBar toolbar;
	private PagingToolBar toolBarPag;

	private List<ColumnConfig> columns;
	private CheckBoxSelectionModel<BeanModel> sm;
	private ColumnModel cm;
	public static Grid<BeanModel> grid;

	private BeanModel selectedModel;
	@SuppressWarnings("unused")
	private List<BeanModel> selectedModels;
	private Integer selectedSize;

	private Listener<MessageBoxEvent> listener;
	private SelectionListener<ButtonEvent> sl_delete;
	
	private GridFilters filters;
	@SuppressWarnings("unused")
	
	private String text = null;

   public static PanelNuevoPagoAdelanto panelnuevopagoadelanto;
	

	public PanelGridPagoAdelanto() {
		super();
		setBodyBorder(false);
		setHeaderVisible(false);
		setIcon(IconHelper.createPath("images/icons/table.png"));
		setHeading(k.pagoadelanto());
		setLayout(new FitLayout());
  
		PagoAdelantos.getPaginate();
	
		btnDelete = new Button(k.eliminar(),IconHelper.createPath("images/icons/delete.gif"));
		btnDelete.setEnabled(false);
		

		toolbar = new ToolBar();
		toolbar.setStyleAttribute("backgroundImage","url(gxt/images/default/panel/white-top-bottom.gif)");
		toolbar.setBorders(true);
		
		filters = new GridFilters();
		filters.addFilter(new StringFilter("fecha"));
		filters.addFilter(new StringFilter("monto"));
		filters.addFilter(new StringFilter("descripcion"));
	
	
		toolbar.add(btnDelete);
		toolbar.add(Utilities.getLabel("Detalle de Adelantos","400px"));


		toolBarPag = new PagingToolBar(Utilities.itemsPerPage);
		toolBarPag.bind(PagoAdelantos.loader);
		toolBarPag.setBorders(true);

		columns = new ArrayList<ColumnConfig>();

		sm = new CheckBoxSelectionModel<BeanModel>();
		sm.setSelectionMode(SelectionMode.SINGLE);

		columns.add(sm.getColumn());
		
		columns.add(new ColumnConfig("fecha", k.fechapago(), 200));
		
		GridCellRenderer<BeanModel> monto = new GridCellRenderer<BeanModel>() {
			@Override
			public Object render(BeanModel model, String property,
					ColumnData config, int rowIndex, int colIndex,
					ListStore<BeanModel> store, Grid<BeanModel> grid) {
				
				String style = "";
				double val = (Double) model.get(property);
				style = "blue";

				return "<span qtitle='"
						+ cm.getColumnById(property).getHeader() + "' qtip='"
						+ val + "' style='font-weight: bold;color:" + style
						+ "'>" + val + "</span>";
			}
		};
		ColumnConfig column = new ColumnConfig("monto",k.monto(), 100);
		column.setAlignment(HorizontalAlignment.LEFT);
		column.setRenderer(monto);
		columns.add(column);	
		columns.add(new ColumnConfig("descripcion", k.observaciones(), 300));
		
		
		cm = new ColumnModel(columns);

		AggregationRowConfig<BeanModel> averages = new AggregationRowConfig<BeanModel>();  
	    averages.setHtml("fecha",k.totaladelanto());  
	    
	    averages.setSummaryType("monto", SummaryType.SUM);  
	    averages.setSummaryFormat("monto", NumberFormat.getDecimalFormat());  
	    
	    cm.addAggregationRow(averages); 
		
				
		grid = new Grid<BeanModel>(PagoAdelantos.store, cm);
		grid.setAutoExpandColumn("descripcion");
		grid.setLoadMask(true);
		grid.setBorders(true);
		grid.addPlugin(sm);
		grid.addPlugin(filters);
		grid.setSelectionModel(sm);
		grid.getSelectionModel().addListener(Events.SelectionChange,
				new Listener<SelectionChangedEvent<BeanModel>>() {

					@Override
					public void handleEvent(SelectionChangedEvent<BeanModel> be) {
						selectedSize = be.getSelection().size();

						if (selectedSize == 0) {
							panelnuevopagoadelanto.unbind();
							btnDelete.setEnabled(false);
						} else if (selectedSize == 1) {
							selectedModel = be.getSelectedItem();
							panelnuevopagoadelanto.bind(selectedModel);
							
							btnDelete.setEnabled(true);
						} else if (selectedSize > 1) {
							selectedModels = be.getSelection();
							panelnuevopagoadelanto.unbind();
							btnDelete.setEnabled(false);
						}

					}

				});

		
		listener = new Listener<MessageBoxEvent>() {

			@Override
			public void handleEvent(MessageBoxEvent be) {
				String button_id = be.getButtonClicked().getItemId();
				if (Dialog.YES == button_id) {
					if (selectedSize == 1) {
						Integer id = selectedModel.get("id");
						Integer contrato_id = selectedModel.get("contrato_id");
						Integer periodo = selectedModel.get("periodo");
						PagoAdelantos.delete(id,contrato_id,periodo);
					} 
//					else if (selectedSize > 1) {
//						String ids = Utilities.toIds(selectedModels);
//					//	PagoAdelantos.deleteAll(ids);
//					}
				}
			}
		};
		sl_delete = new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				String mensaje = "";
				if (selectedSize == 1) {
					String nombres = String.valueOf(selectedModel.get("monto"));
					mensaje = msg.empleadoEstaSeguro(k.monto()+" " +nombres);

				} else if (selectedSize > 1) {
					mensaje = k.eliminarAll();
				}
				MessageBox.confirm(k.confirmacion(), mensaje, listener)
						.getDialog().getButtonById(Dialog.YES).setText(k.si());

			}
		};

		btnDelete.addSelectionListener(sl_delete);

		setTopComponent(toolbar);
		//setBottomComponent(toolBarPag);

		add(grid);

	}
	
	
}
